package com.seu.vcampus.client;

import com.seu.vcampus.message.Message;
import com.seu.vcampus.vo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 虚拟校园客户端类
 * 负责与服务器通信
 * 
 * @author 虚拟校园开发团队
 * @since 1.0.0
 */
public class VCampusClient {
    private static final Logger logger = LoggerFactory.getLogger(VCampusClient.class);
    
    private final String serverHost;
    private final int serverPort;
    private Socket socket;
    private ObjectOutputStream out;
    private ObjectInputStream in;
    private String sessionId;
    private User currentUser;
    
    public VCampusClient(String serverHost, int serverPort) {
        this.serverHost = serverHost;
        this.serverPort = serverPort;
    }
    
    /**
     * 连接到服务器
     * @return 是否连接成功
     */
    public boolean connect() {
        try {
            socket = new Socket(serverHost, serverPort);
            out = new ObjectOutputStream(socket.getOutputStream());
            in = new ObjectInputStream(socket.getInputStream());
            
            logger.info("连接到服务器: {}:{}", serverHost, serverPort);
            return true;
        } catch (IOException e) {
            logger.error("连接服务器失败: {}", e.getMessage());
            return false;
        }
    }
    
    /**
     * 断开连接
     */
    public void disconnect() {
        try {
            // 先发送关闭信号给服务器
            if (socket != null && !socket.isClosed()) {
                socket.shutdownOutput();
                try {
                    Thread.sleep(100); // 给服务器处理时间
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
            
            // 安全关闭流
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    logger.debug("关闭输出流时出错", e);
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    logger.debug("关闭输入流时出错", e);
                }
            }
            if (socket != null) {
                try {
                    if (!socket.isClosed()) {
                        socket.close();
                    }
                } catch (IOException e) {
                    logger.debug("关闭socket时出错", e);
                }
            }
            logger.info("已安全断开与服务器的连接");
        } catch (Exception e) {
            logger.error("断开连接时出错", e);
        }
    }
    
    /**
     * 发送消息到服务器
     * @param message 消息对象
     * @return 响应消息
     * @throws IOException 如果通信失败
     * @throws ClassNotFoundException 如果反序列化失败
     */
    public Message sendMessage(Message message) throws IOException, ClassNotFoundException {
        if (out == null || in == null) {
            throw new IOException("未连接到服务器");
        }
        
        // 添加会话ID
        if (sessionId != null) {
            message.setSessionId(sessionId);
        }
        
        out.writeObject(message);
        out.flush();
        
        Message response = (Message) in.readObject();
        
        // 更新会话ID
        if (response.getSessionId() != null) {
            sessionId = response.getSessionId();
        }
        
        return response;
    }
    
    /**
     * 登录
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    public boolean login(String username, String password) {
        try {
            // 创建一个临时的User对象用于登录
            User loginUser = new User();
            loginUser.setUsername(username);
            loginUser.setPassword(password);
            
            Message request = new Message(Message.Type.LOGIN_REQUEST, loginUser);
            Message response = sendMessage(request);
            
            if (response.isSuccess()) {
                currentUser = (User) response.getPayload();
                logger.info("用户 {} 登录成功", username);
                return true;
            } else {
                logger.warn("用户 {} 登录失败: {}", username, response.getErrorMessage());
                return false;
            }
        } catch (Exception e) {
            logger.error("登录时出错", e);
            return false;
        }
    }
    
    /**
     * 注册
     * @param user 用户对象
     * @return 注册结果
     */
    public boolean register(User user) {
        try {
            Message request = new Message(Message.Type.REGISTER_REQUEST, user);
            Message response = sendMessage(request);
            
            return response.isSuccess();
        } catch (Exception e) {
            logger.error("注册时出错", e);
            return false;
        }
    }
    
    /**
     * 注销
     */
    public void logout() {
        try {
            if (sessionId != null) {
                Message request = new Message(Message.Type.LOGOUT_REQUEST, null);
                sendMessage(request);
            }
        } catch (Exception e) {
            logger.error("注销时出错", e);
        } finally {
            sessionId = null;
            currentUser = null;
        }
    }
    
    /**
     * 获取当前用户
     * @return 当前登录用户
     */
    public User getCurrentUser() {
        return currentUser;
    }
    
    /**
     * 获取会话ID
     * @return 会话ID
     */
    public String getSessionId() {
        return sessionId;
    }
}